/**
 *
 * @param word 关键字： (顶级画质), 顶级画质, [顶级画质]等
 * @returns 如果合法，返回处理之后的关键字，如果不合法，返回 false
 *
 * 合法的 word 例如： 顶级画质，(顶级画质), 顶级画质, [顶级画质]，
 * 不合法： (（（（（顶级画质)， [顶级画质]]]]
 *  */
const isValidKeywod = (word) => {
  const regex = /([\w\u4e00-\u9fa5]+)/g;
  const matches = word.match(regex);
  if (matches) {
    let ele = matches[0];
    if (ele.length === word.length) {
      return ele;
    } else {
      // 判断 [[   toto   ]], 符合是否对称，剩下的是否是
      let [left, right] = word.split(ele);
      left = left?.trim();
      right = right?.trim();
      let _left = "";
      let bracketMapper = {
        "[": "]",
        "（": "）",
        "(": ")",
      };
      for (let i = 0; i < left.length; i++) {
        let char = left[i];
        let newChart = bracketMapper[char];
        if (newChart) {
          _left += newChart;
        } else {
          return false;
        }
      }
      return _left === right ? ele : false;
    }
  }
  return false;
};

// 得到合法的关键字
const getValidKeywords = (wrods) => {
  let newWords = wrods?.filter((keyword) => keyword)?.map((ele) => ele?.trim());
  let ws = [];
  newWords.forEach((word) => {
    let newWord = isValidKeywod(word);
    if (newWord) {
      ws.push(newWord);
    }
  });
  return ws;
};

let result = "";
let keywords = result.split("，").join(",").split(",");
let validKeywords = getValidKeywords(_keywords);

/**
 *
 * @param name 点击 tag 时候
 * @returns index 为对应 name 在 result 中所在的索引位置，_index 是 name 在 keywords所在的索引，
 */
const findNameIndex = (name, keywords) => {
  // 关键字所在的索引
  let _index = 0;
  for (let i = 0; i < keywords.length; i++) {
    let word = keywords[i];
    let newWord = isValidKeywod(word);
    if (newWord && newWord === name) {
      _index = i;
      break;
    }
  }
  let preStr = keywords.slice(0, _index).join(",");
  // 对应字，name 关键字，在 result 所在的索引
  let index = preStr.length ? preStr.length + 1 : preStr.length;
  // 第一个元素为空的时候
  if (_index === 1 && preStr === "") {
    preStr = " ";
    index = 1;
  }
  return [index, _index];
};

const handleIconClick = (type, name) => {
  let [resultIndex, keywordsIndex] = findNameIndex(name, keywords);
  let word = keywords[keywordsIndex];
  const typeBracketMapper = {
    plus: {
      leftBracket: "(",
      rightBracket: ")",
    },
    minus: {
      leftBracket: "[",
      rightBracket: "]",
    },
  };
  const { leftBracket, rightBracket } = typeBracketMapper[type];
  let left = result.slice(0, resultIndex);
  let rightIndex = resultIndex + word.length;
  let right = result.slice(rightIndex);
  let char = word[0];
  let center = word;
  if (char === "[") {
    // console.log("当前 tag 减少类型");
    if (leftBracket === "[") {
      center = `${leftBracket}${word}${rightBracket}`;
    } else {
      center = word.slice(1, word.length - 1);
    }
  } else if (char === "(") {
    // console.log("当前 tag 添加类型");
    if (leftBracket === "[") {
      center = word.slice(1, word.length - 1);
    } else {
      center = `${leftBracket}${word}${rightBracket}`;
    }
  } else {
    center = `${leftBracket}${word}${rightBracket}`;
  }
  let newResult = `${left}${center}${right}`;
  return newResult;
  //   setResult(newResult);
  // console.log("left", left, "right", right, "center", center);
};

const removeNameFromResult = (name) => {
  if (validKeywords.some((ele) => ele === name)) {
    // 如果选择的 tag 包含，那么需要给对应 name 删除
    let [resultIndex, keywordsIndex] = findNameIndex(name);
    let word = keywords[keywordsIndex];
    let left = resultIndex
      ? result.slice(0, resultIndex - 1)
      : result.slice(0, resultIndex);
    let rightIndex = keywordsIndex
      ? resultIndex + word.length
      : resultIndex + word.length + 1;
    let right = result.slice(rightIndex);
    let newResult = left + right;
    return newResult;
    // setResult(newResult);
  } else {
    let newResult = result ? `${result}，${name}` : name;
    return newResult;
    // setResult(newResult);
  }
};
